/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: service_provider.cpp
 *
 * Purpose: service endian base class implementation for 'COM' Functional
 *
 * Developer:
 *   wen.gu , 2020-06-15
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#define LOG_TAG "SRVP"
#include "panda/com/service_provider.h"
#include "panda/sys/ipc_service_provider.h"

#include "panda/core/log.h"

namespace panda
{
namespace com
{
/******************************************************************************
 **    MACROS
 ******************************************************************************/

#define MakeServiceRequestHandlePtr() std::make_shared<ServiceRequestHandle>()


#define RegDefaultMethod(name, method)  do{                             \
        if (method) {                                                   \
            ServiceOnStateChangeFunction tempMethod = method;           \
            registerMethod(name, [this, tempMethod](ServiceRequestHandlePtr rhdl, const std::string& funcName, const panda::core::Value& param) \
            {   Value reply;                                            \
                ServiceState newState = mImpl->funcName2State(funcName);\
                if (newState != mImpl->mState){                         \
                    panda::core::Error2Json(tempMethod(), reply);       \
                    mImpl->mState = newState;                           \
                }else{ panda::core::Error2Json(PandaErrc::OK, reply);}  \
                    sendResponse(rhdl, reply);                          \
            });                                                         \
        } \
    }while (0)

/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

using PandaErrc = panda::core::PandaErrc;
using Value = panda::core::Value;
using IpcServiceProvider = panda::sys::IpcServiceProvider;
using IpcPacketData = panda::sys::IpcPacketData;
using IpcServiceRequestHandlePtr = panda::sys::IpcServiceRequestHandlePtr;



enum class ServiceState: uint8_t
{
    Stopped = 0,
    Started = 1,
    Suspend = 2,
};


class ServiceProvider::impl
{
public:
    ServiceState mState = ServiceState::Stopped;
    IpcServiceProvider* mService;

public:
    bool isDefaultMehotd(const std::string& name)
    {
        return (name == SRV_METHOD_ON_RESUME) || (name == SRV_METHOD_ON_STOP) || (name == SRV_METHOD_ON_SUSPEND);
    }

    ServiceState funcName2State(const std::string& methodName)
    {
        if (methodName == SRV_METHOD_ON_RESUME)
        {
            return ServiceState::Started;
        }
        else if (methodName == SRV_METHOD_ON_STOP)
        {
            return ServiceState::Stopped;
        }
        else if (methodName == SRV_METHOD_ON_SUSPEND)
        {
            return ServiceState::Suspend;
        }

        return ServiceState::Stopped; //todo, fix me??
    }
};

class ServiceRequestHandle
{
public:
    IpcServiceRequestHandlePtr irhdl = nullptr;

};
/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/

 /**
 * srvName: the name of service.
 * multiThreadCnt: the count of thread for process request.
 * mode: how to work for current service.
 *
 */
ServiceProvider::ServiceProvider(const std::string& srvName, uint32_t multiThreadCnt /*= 1*/, ServiceWorkMode mode /*= ServiceWorkMode::kLocalOnly*/)
    :mImpl(new impl)
{
    if (mode == ServiceWorkMode::kLocalOnly)
    { 
        mImpl->mService = new IpcServiceProvider(srvName, multiThreadCnt);
    }
    else
    {
        LOGE("unsupport this work mode(%d) for service at now\n", (int32_t)mode);
        assert(0);
    }
    
}
ServiceProvider::~ServiceProvider()
{
    if (mImpl->mService)
    {
        delete mImpl->mService;
    }
}


PandaErrc ServiceProvider::start(ServiceStateManagerCallbacks* callbacks /** = nullptr*/)
{
    if (callbacks)
    {
        RegDefaultMethod(SRV_METHOD_ON_RESUME, callbacks->onResume);
        RegDefaultMethod(SRV_METHOD_ON_SUSPEND, callbacks->onSuspend);
        RegDefaultMethod(SRV_METHOD_ON_STOP, callbacks->onStop);
    }
    return mImpl->mService->start();
}

PandaErrc ServiceProvider::stop()
{
    return mImpl->mService->stop();
}


/** api for method */
PandaErrc ServiceProvider::registerMethod(const std::string& name, ServiceMethodHandler handler)
{
    if (name.empty() || !handler) return PandaErrc::BadParameter;
    return mImpl->mService->registerMethod(name, [this, handler](IpcServiceRequestHandlePtr rhdl, const std::string& method, const IpcPacketData& data)
    {    
        ServiceRequestHandlePtr srhdl = MakeServiceRequestHandlePtr();
        srhdl->irhdl = rhdl;
        if ((mImpl->mState == ServiceState::Started) || (mImpl->isDefaultMehotd(method)))
        {
            Value param;

            if (data.payload && (data.size > 0))
            {
                panda::core::JsonParse((const char*)data.payload.get(), (const char*)data.payload.get() + data.size, param);
            }
            handler(srhdl, method, param);
        }
        else
        {
            Value reply;
            panda::core::Error2Json(PandaErrc::InvalidStatus, reply);
            sendResponse(srhdl, reply);
        }
    });
}

PandaErrc ServiceProvider::sendResponse(ServiceRequestHandlePtr reqHdl, const Value& data)
{
    if (!reqHdl) return PandaErrc::BadParameter;

    std::string paramStr;
    if (panda::core::JsonWriteRaw(data, paramStr))
    {
        return mImpl->mService->sendResponse(reqHdl->irhdl, (const uint8_t*)paramStr.data(), (uint32_t)paramStr.size());
    }
    
    return PandaErrc::BadParameter;
}

/** api for signal */
void ServiceProvider::emitSignal(const std::string& sigName, const Value& data)
{
    /** todo, to process the service state, e.g. suspend, stopped */
    if (sigName.empty()) return ;

    std::string paramStr;
    if (panda::core::JsonWriteRaw(data, paramStr))
    {
        mImpl->mService->emitSignal(sigName, (const uint8_t*)paramStr.data(), (uint32_t)paramStr.size());
    }
}

} /** namespace com */
} /** namespace panda */


